﻿// Admin.NET 项目的版权、商标、专利和其他相关权利均受相应法律法规的保护。使用本项目应遵守相关法律法规和许可证的要求。
//
// 本项目主要遵循 MIT 许可证和 Apache 许可证（版本 2.0）进行分发和使用。许可证位于源代码树根目录中的 LICENSE-MIT 和 LICENSE-APACHE 文件。
//
// 不得利用本项目从事危害国家安全、扰乱社会秩序、侵犯他人合法权益等法律法规禁止的活动！任何基于本项目二次开发而产生的一切法律纠纷和责任，我们不承担任何责任！

using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using Admin.NET.Application.Entity;
using Admin.NET.Core.Service;
using Furion.DatabaseAccessor;
using Furion.FriendlyException;
using Mapster;
using Microsoft.AspNetCore.Http;
using SqlSugar;

namespace Admin.NET.Application;

/// <summary>
/// 检验方案服务 🧩
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public class inspectionschemeService : IDynamicApiController, ITransient
{
    private readonly SqlSugarRepository<inspectionscheme> _inspectionschemeRep;
    private readonly ISqlSugarClient _sqlSugarClient;

    public inspectionschemeService(SqlSugarRepository<inspectionscheme> inspectionschemeRep, ISqlSugarClient sqlSugarClient)
    {
        _inspectionschemeRep = inspectionschemeRep;
        _sqlSugarClient = sqlSugarClient;
    }

    /// <summary>
    /// 分页查询检验方案 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("分页查询检验方案")]
    [ApiDescriptionSettings(Name = "Page"), HttpPost]
    public async Task<SqlSugarPagedList<inspectionschemeOutput>> Page(PageinspectionschemeInput input)
    {
        input.Keyword = input.Keyword?.Trim();
        var query = _inspectionschemeRep.AsQueryable()
            .WhereIF(!string.IsNullOrWhiteSpace(input.Keyword), u => u.schemename.Contains(input.Keyword) || u.schemedesc.Contains(input.Keyword))
            .WhereIF(!string.IsNullOrWhiteSpace(input.schemename), u => u.schemename.Contains(input.schemename.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.schemedesc), u => u.schemedesc.Contains(input.schemedesc.Trim()))
            .WhereIF(input.inspectionprojectid != null, u => u.inspectionprojectid == input.inspectionprojectid)
            .LeftJoin<inspectionproject>((u, inspectionproject) => u.inspectionprojectid == inspectionproject.Id)
            .Select((u, inspectionproject) => new inspectionschemeOutput
            {
                Id = u.Id,
                schemename = u.schemename,
                schemetype = u.schemetype,
                inspectionprojectid = u.inspectionprojectid,
                inspectionprojectFkDisplayName = $"{inspectionproject.projectname}",
                schemedesc = u.schemedesc,
                CreateTime = u.CreateTime,
                UpdateTime = u.UpdateTime,
                CreateUserId = u.CreateUserId,
                CreateUserName = u.CreateUserName,
                UpdateUserId = u.UpdateUserId,
                UpdateUserName = u.UpdateUserName,
                IsDelete = u.IsDelete,
            });
		return await query.OrderBuilder(input).ToPagedListAsync(input.Page, input.PageSize);
    }

    /// <summary>
    /// 获取检验方案详情 ℹ️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("获取检验方案详情")]
    [ApiDescriptionSettings(Name = "Detail"), HttpGet]
    public async Task<inspectionscheme> Detail([FromQuery] QueryByIdinspectionschemeInput input)
    {
        return await _inspectionschemeRep.GetFirstAsync(u => u.Id == input.Id);
    }

    /// <summary>
    /// 增加检验方案 ➕
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("增加检验方案")]
    [ApiDescriptionSettings(Name = "Add"), HttpPost]
    public async Task<long> Add(AddinspectionschemeInput input)
    {
        var entity = input.Adapt<inspectionscheme>();
        return await _inspectionschemeRep.InsertAsync(entity) ? entity.Id : 0;
    }

    /// <summary>
    /// 更新检验方案 ✏️
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("更新检验方案")]
    [ApiDescriptionSettings(Name = "Update"), HttpPost]
    public async Task Update(UpdateinspectionschemeInput input)
    {
        var entity = input.Adapt<inspectionscheme>();
        await _inspectionschemeRep.AsUpdateable(entity)
        .ExecuteCommandAsync();
    }

    /// <summary>
    /// 删除检验方案 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("删除检验方案")]
    [ApiDescriptionSettings(Name = "Delete"), HttpPost]
    public async Task Delete(DeleteinspectionschemeInput input)
    {
        var entity = await _inspectionschemeRep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _inspectionschemeRep.FakeDeleteAsync(entity);   //假删除
        //await _inspectionschemeRep.DeleteAsync(entity);   //真删除
    }

    /// <summary>
    /// 批量删除检验方案 ❌
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("批量删除检验方案")]
    [ApiDescriptionSettings(Name = "BatchDelete"), HttpPost]
    public async Task<int> BatchDelete([Required(ErrorMessage = "主键列表不能为空")]List<DeleteinspectionschemeInput> input)
    {
        var exp = Expressionable.Create<inspectionscheme>();
        foreach (var row in input) exp = exp.Or(it => it.Id == row.Id);
        var list = await _inspectionschemeRep.AsQueryable().Where(exp.ToExpression()).ToListAsync();
   
        return await _inspectionschemeRep.FakeDeleteAsync(list);   //假删除
        //return await _inspectionschemeRep.DeleteAsync(list);   //真删除
    }
    
    /// <summary>
    /// 获取下拉列表数据 🔖
    /// </summary>
    /// <returns></returns>
    [DisplayName("获取下拉列表数据")]
    [ApiDescriptionSettings(Name = "DropdownData"), HttpPost]
    public async Task<Dictionary<string, dynamic>> DropdownData(DropdownDatainspectionschemeInput input)
    {
        var inspectionprojectidData = await _inspectionschemeRep.Context.Queryable<inspectionproject>()
            .InnerJoinIF<inspectionscheme>(input.FromPage, (u, r) => u.Id == r.inspectionprojectid)
            .Select(u => new {
                Value = u.Id,
                Label = $"{u.projectname}"
            }).ToListAsync();
        return new Dictionary<string, dynamic>
        {
            { "inspectionprojectid", inspectionprojectidData },
        };
    }
    
    /// <summary>
    /// 导出检验方案记录 🔖
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [DisplayName("导出检验方案记录")]
    [ApiDescriptionSettings(Name = "Export"), HttpPost, NonUnify]
    public async Task<IActionResult> Export(PageinspectionschemeInput input)
    {
        var list = (await Page(input)).Items?.Adapt<List<ExportinspectionschemeOutput>>() ?? new();
        if (input.SelectKeyList?.Count > 0) list = list.Where(x => input.SelectKeyList.Contains(x.Id)).ToList();
        return ExcelHelper.ExportTemplate(list, "检验方案导出记录");
    }
    
    /// <summary>
    /// 下载检验方案数据导入模板 ⬇️
    /// </summary>
    /// <returns></returns>
    [DisplayName("下载检验方案数据导入模板")]
    [ApiDescriptionSettings(Name = "Import"), HttpGet, NonUnify]
    public IActionResult DownloadTemplate()
    {
        return ExcelHelper.ExportTemplate(new List<ExportinspectionschemeOutput>(), "检验方案导入模板", (_, info) =>
        {
            if (nameof(ExportinspectionschemeOutput.inspectionprojectFkDisplayName) == info.Name) return _inspectionschemeRep.Context.Queryable<inspectionproject>().Select(u => $"{u.projectname}").Distinct().ToList();
            return null;
        });
    }
    
    /// <summary>
    /// 导入检验方案记录 💾
    /// </summary>
    /// <returns></returns>
    [DisplayName("导入检验方案记录")]
    [ApiDescriptionSettings(Name = "Import"), HttpPost, NonUnify, UnitOfWork]
    public IActionResult ImportData([Required] IFormFile file)
    {
        lock (this)
        {
            var stream = ExcelHelper.ImportData<ImportinspectionschemeInput, inspectionscheme>(file, (list, markerErrorAction) =>
            {
                _sqlSugarClient.Utilities.PageEach(list, 2048, pageItems =>
                {
                    // 链接 检验项目
                    var inspectionprojectidLabelList = pageItems.Where(x => x.inspectionprojectFkDisplayName != null).Select(x => x.inspectionprojectFkDisplayName).Distinct().ToList();
                    if (inspectionprojectidLabelList.Any()) {
                        var inspectionprojectidLinkMap = _inspectionschemeRep.Context.Queryable<inspectionproject>().Where(u => inspectionprojectidLabelList.Contains($"{u.projectname}")).ToList().ToDictionary(u => $"{u.projectname}", u => u.Id);
                        pageItems.ForEach(e => {
                            e.inspectionprojectid = inspectionprojectidLinkMap.GetValueOrDefault(e.inspectionprojectFkDisplayName ?? "");
                            if (e.inspectionprojectid == null) e.Error = "检验项目链接失败";
                        });
                    }
                    
                    // 校验并过滤必填基本类型为null的字段
                    var rows = pageItems.Where(x => {
                        if (!string.IsNullOrWhiteSpace(x.Error)) return false;
                        if (x.schemetype == null){
                            x.Error = "类型不能为空";
                            return false;
                        }
                        return true;
                    }).Adapt<List<inspectionscheme>>();
                    
                    var storageable = _inspectionschemeRep.Context.Storageable(rows)
                        .SplitError(it => it.Item.schemename?.Length > 32, "名称长度不能超过32个字符")
                        .SplitError(it => it.Item.schemedesc?.Length > 32, "描述长度不能超过32个字符")
                        .SplitInsert(_ => true)
                        .ToStorage();
                    
                    storageable.BulkCopy();
                    storageable.BulkUpdate();
                    
                    // 标记错误信息
                    markerErrorAction.Invoke(storageable, pageItems, rows);
                });
            });
            
            return stream;
        }
    }
}
